package gofunc

import (
	"reflect"
)

type StructFunc struct {
}

//将任意结构体的字段序列化为byte
//常用于协议解析
func (self *StructFunc) EncodeToByte(st interface{}) []byte {
	result := []byte{}
	intfunc := IntFunc{}
	ref := reflect.ValueOf(st).Elem()
	for i := 0; i < ref.NumField(); i++ {
		f := ref.Field(i)
		switch f.Kind() {
		case reflect.Uint8:
			result = append(result, byte(f.Uint()))
		case reflect.Uint16:
			bl := intfunc.Uint16ToByte(uint16(f.Uint()))
			result = append(result, bl...)
		case reflect.Slice:
			for i := 0; i < f.Len(); i++ {
				e := f.Index(i)
				switch e.Kind() {
				case reflect.Uint8: //byte 数组
					result = append(result, byte(e.Uint()))
				}
			}

		}

	}
	return result
}
